package bb.lanxing.mvp.view.widget;

import static android.content.Context.INPUT_METHOD_SERVICE;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import android.view.inputmethod.InputMethodManager;

import androidx.appcompat.widget.AppCompatEditText;
import androidx.core.content.ContextCompat;
import androidx.core.internal.view.SupportMenu;
import androidx.core.view.ViewCompat;

import bb.lanxing.R;


public class PinEntryEditText extends AppCompatEditText {
    public static final String DEFAULT_MASK = "●";
    private static final String XML_NAMESPACE_ANDROID = "http://schemas.android.com/apk/res/android";
    protected boolean mAnimate;
    protected int mAnimatedType;
    protected float[] mCharBottom;
    protected Paint mCharPaint;
    protected float mCharSize;
    protected OnClickListener mClickListener;
    protected ColorStateList mColorStates;
    protected int[] mColors;
    protected boolean mHasError;
    protected boolean mIsDigitSquare;
    protected Paint mLastCharPaint;
    protected RectF[] mLineCoords;
    protected float mLineStroke;
    protected float mLineStrokeSelected;
    protected Paint mLinesPaint;
    protected String mMask;
    protected StringBuilder mMaskChars;
    protected int mMaxLength;
    protected float mNumChars;
    protected OnPinEnteredListener mOnPinEnteredListener;
    protected ColorStateList mOriginalTextColors;
    protected Drawable mPinBackground;
    protected String mSingleCharHint;
    protected Paint mSingleCharPaint;
    protected float mSpace;
    protected int[][] mStates;
    protected float mTextBottomPadding;
    protected Rect mTextHeight;

    public interface OnPinEnteredListener {
        void onPinEntered(CharSequence charSequence);
    }

    public PinEntryEditText(Context context) {
        super(context);
        this.mMask = null;
        this.mMaskChars = null;
        this.mSingleCharHint = null;
        this.mAnimatedType = 0;
        this.mSpace = 24.0f;
        this.mNumChars = 4.0f;
        this.mTextBottomPadding = 8.0f;
        this.mMaxLength = 4;
        this.mTextHeight = new Rect();
        this.mIsDigitSquare = false;
        this.mOnPinEnteredListener = null;
        this.mLineStroke = 1.0f;
        this.mLineStrokeSelected = 2.0f;
        this.mAnimate = false;
        this.mHasError = false;
        this.mStates = new int[][]{new int[]{16842913}, new int[]{16842914}, new int[]{16842908}, new int[]{-16842908}};
        this.mColors = new int[]{-16711936, SupportMenu.CATEGORY_MASK, ViewCompat.MEASURED_STATE_MASK, -7829368};
        this.mColorStates = new ColorStateList(this.mStates, this.mColors);
    }

    public PinEntryEditText(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        this.mMask = null;
        this.mMaskChars = null;
        this.mSingleCharHint = null;
        this.mAnimatedType = 0;
        this.mSpace = 24.0f;
        this.mNumChars = 4.0f;
        this.mTextBottomPadding = 8.0f;
        this.mMaxLength = 4;
        this.mTextHeight = new Rect();
        this.mIsDigitSquare = false;
        this.mOnPinEnteredListener = null;
        this.mLineStroke = 1.0f;
        this.mLineStrokeSelected = 2.0f;
        this.mAnimate = false;
        this.mHasError = false;
        this.mStates = new int[][]{new int[]{16842913}, new int[]{16842914}, new int[]{16842908}, new int[]{-16842908}};
        this.mColors = new int[]{-16711936, SupportMenu.CATEGORY_MASK, ViewCompat.MEASURED_STATE_MASK, -7829368};
        this.mColorStates = new ColorStateList(this.mStates, this.mColors);
        init(context, attributeSet);
    }

    public PinEntryEditText(Context context, AttributeSet attributeSet, int i) {
        super(context, attributeSet, i);
        this.mMask = null;
        this.mMaskChars = null;
        this.mSingleCharHint = null;
        this.mAnimatedType = 0;
        this.mSpace = 24.0f;
        this.mNumChars = 4.0f;
        this.mTextBottomPadding = 8.0f;
        this.mMaxLength = 4;
        this.mTextHeight = new Rect();
        this.mIsDigitSquare = false;
        this.mOnPinEnteredListener = null;
        this.mLineStroke = 1.0f;
        this.mLineStrokeSelected = 2.0f;
        this.mAnimate = false;
        this.mHasError = false;
        this.mStates = new int[][]{new int[]{16842913}, new int[]{16842914}, new int[]{16842908}, new int[]{-16842908}};
        this.mColors = new int[]{-16711936, SupportMenu.CATEGORY_MASK, ViewCompat.MEASURED_STATE_MASK, -7829368};
        this.mColorStates = new ColorStateList(this.mStates, this.mColors);
        init(context, attributeSet);
    }

    public void setMaxLength(int i) {
        this.mMaxLength = i;
        this.mNumChars = i;
        setFilters(new InputFilter[]{new InputFilter.LengthFilter(i)});
        setText((CharSequence) null);
        invalidate();
    }

    public void setMask(String str) {
        this.mMask = str;
        this.mMaskChars = null;
        invalidate();
    }

    public void setSingleCharHint(String str) {
        this.mSingleCharHint = str;
        invalidate();
    }

    private void init(Context context, AttributeSet attributeSet) {
        float f = context.getResources().getDisplayMetrics().density;
        this.mLineStroke *= f;
        this.mLineStrokeSelected *= f;
        this.mSpace *= f;
        this.mTextBottomPadding = f * this.mTextBottomPadding;
        TypedArray obtainStyledAttributes = context.obtainStyledAttributes(attributeSet, R.styleable.PinEntryEditText, 0, 0);
        try {
            TypedValue typedValue = new TypedValue();
            obtainStyledAttributes.getValue(R.styleable.PinEntryEditText_pinAnimationType, typedValue);
            this.mAnimatedType = typedValue.data;
            this.mMask = obtainStyledAttributes.getString(R.styleable.PinEntryEditText_pinCharacterMask);
            this.mSingleCharHint = obtainStyledAttributes.getString(R.styleable.PinEntryEditText_pinRepeatedHint);
            this.mLineStroke = obtainStyledAttributes.getDimension(R.styleable.PinEntryEditText_pinLineStroke, this.mLineStroke);
            this.mLineStrokeSelected = obtainStyledAttributes.getDimension(R.styleable.PinEntryEditText_pinLineStrokeSelected, this.mLineStrokeSelected);
            this.mSpace = obtainStyledAttributes.getDimension(R.styleable.PinEntryEditText_pinCharacterSpacing, this.mSpace);
            this.mTextBottomPadding = obtainStyledAttributes.getDimension(R.styleable.PinEntryEditText_pinTextBottomPadding, this.mTextBottomPadding);
            this.mIsDigitSquare = obtainStyledAttributes.getBoolean(R.styleable.PinEntryEditText_pinBackgroundIsSquare, this.mIsDigitSquare);
            this.mPinBackground = obtainStyledAttributes.getDrawable(R.styleable.PinEntryEditText_pinBackgroundDrawable);
            ColorStateList colorStateList = obtainStyledAttributes.getColorStateList(R.styleable.PinEntryEditText_pinLineColors);
            if (colorStateList != null) {
                this.mColorStates = colorStateList;
            }
            obtainStyledAttributes.recycle();
            this.mCharPaint = new Paint(getPaint());
            this.mLastCharPaint = new Paint(getPaint());
            this.mSingleCharPaint = new Paint(getPaint());
            Paint paint = new Paint(getPaint());
            this.mLinesPaint = paint;
            paint.setStrokeWidth(this.mLineStroke);
            TypedValue typedValue2 = new TypedValue();
            // TODO: 12/27/2023 need add theme
//            context.getTheme().resolveAttribute(R.attr.colorControlActivated, typedValue2, true);
            this.mColors[0] = typedValue2.data;
            this.mColors[1] = isInEditMode() ? -7829368 : ContextCompat.getColor(context, R.color.pin_normal);
            this.mColors[2] = isInEditMode() ? -7829368 : ContextCompat.getColor(context, R.color.pin_normal);
            setBackgroundResource(0);
            int attributeIntValue = attributeSet.getAttributeIntValue(XML_NAMESPACE_ANDROID, "maxLength", 4);
            this.mMaxLength = attributeIntValue;
            this.mNumChars = attributeIntValue;
            super.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
                @Override
                public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
                    return false;
                }

                @Override
                public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
                    return false;
                }

                @Override
                public void onDestroyActionMode(ActionMode actionMode) {
                }

                @Override
                public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
                    return false;
                }
            });
            super.setOnClickListener(view -> {
                PinEntryEditText pinEntryEditText = PinEntryEditText.this;
                pinEntryEditText.setSelection(pinEntryEditText.getText().length());
                if (PinEntryEditText.this.mClickListener != null) {
                    PinEntryEditText.this.mClickListener.onClick(view);
                }
            });
            super.setOnLongClickListener(view -> {
                PinEntryEditText pinEntryEditText = PinEntryEditText.this;
                pinEntryEditText.setSelection(pinEntryEditText.getText().length());
                return true;
            });
            if ((getInputType() & 128) == 128 && TextUtils.isEmpty(this.mMask)) {
                this.mMask = DEFAULT_MASK;
            } else if ((getInputType() & 16) == 16 && TextUtils.isEmpty(this.mMask)) {
                this.mMask = DEFAULT_MASK;
            }
            if (!TextUtils.isEmpty(this.mMask)) {
                this.mMaskChars = getMaskChars();
            }
            getPaint().getTextBounds("|", 0, 1, this.mTextHeight);
            this.mAnimate = this.mAnimatedType > -1;
        } catch (Throwable th) {
            obtainStyledAttributes.recycle();
            throw th;
        }
    }

    @Override
    public void setInputType(int i) {
        super.setInputType(i);
        if ((i & 128) == 128 || (i & 16) == 16) {
            if (TextUtils.isEmpty(this.mMask)) {
                setMask(DEFAULT_MASK);
                return;
            }
            return;
        }
        setMask(null);
    }

    @Override
    protected void onSizeChanged(int i, int i2, int i3, int i4) {
        int paddingStart;
        float f;
        super.onSizeChanged(i, i2, i3, i4);
        ColorStateList textColors = getTextColors();
        this.mOriginalTextColors = textColors;
        if (textColors != null) {
            this.mLastCharPaint.setColor(textColors.getDefaultColor());
            this.mCharPaint.setColor(this.mOriginalTextColors.getDefaultColor());
            this.mSingleCharPaint.setColor(getCurrentHintTextColor());
        }
        int width = (getWidth() - ViewCompat.getPaddingEnd(this)) - ViewCompat.getPaddingStart(this);
        float f2 = this.mSpace;
        if (f2 < 0.0f) {
            this.mCharSize = width / ((this.mNumChars * 2.0f) - 1.0f);
        } else {
            float f3 = this.mNumChars;
            this.mCharSize = (width - (f2 * (f3 - 1.0f))) / f3;
        }
        float f4 = this.mNumChars;
        this.mLineCoords = new RectF[(int) f4];
        this.mCharBottom = new float[(int) f4];
        int height = getHeight() - getPaddingBottom();
        int i5 = 1;
        if (ViewCompat.getLayoutDirection(this) == 1) {
            i5 = -1;
            paddingStart = (int) ((getWidth() - ViewCompat.getPaddingStart(this)) - this.mCharSize);
        } else {
            paddingStart = ViewCompat.getPaddingStart(this);
        }
        for (int i6 = 0; i6 < this.mNumChars; i6++) {
            float f5 = paddingStart;
            float f6 = height;
            this.mLineCoords[i6] = new RectF(f5, f6, this.mCharSize + f5, f6);
            if (this.mPinBackground != null) {
                if (this.mIsDigitSquare) {
                    this.mLineCoords[i6].top = getPaddingTop();
                    RectF[] rectFArr = this.mLineCoords;
                    rectFArr[i6].right = rectFArr[i6].width() + f5;
                } else {
                    this.mLineCoords[i6].top -= this.mTextHeight.height() + (this.mTextBottomPadding * 2.0f);
                }
            }
            float f7 = this.mSpace;
            if (f7 < 0.0f) {
                f = f5 + (i5 * this.mCharSize * 2.0f);
            } else {
                f = f5 + (i5 * (this.mCharSize + f7));
            }
            paddingStart = (int) f;
            this.mCharBottom[i6] = this.mLineCoords[i6].bottom - this.mTextBottomPadding;
        }
    }

    @Override
    protected void onMeasure(int i, int i2) {
        int paddingLeft;
        float f;
        float f2;
        float f3;
        int size = 0;
        float f4 = 0f;
        float f5 = 0f;
        float f6 = 0f;
        if (this.mIsDigitSquare) {
            int mode = MeasureSpec.getMode(i);
            int mode2 = MeasureSpec.getMode(i2);
            if (mode == 1073741824) {
                paddingLeft = MeasureSpec.getSize(i);
                f = paddingLeft;
                f2 = this.mNumChars;
                f3 = this.mSpace;
            } else {
                if (mode2 == 1073741824) {
                    size = MeasureSpec.getSize(i2);
                    f4 = this.mNumChars;
                    f5 = size * f4;
                    f6 = this.mSpace;
                } else if (mode == Integer.MIN_VALUE) {
                    paddingLeft = MeasureSpec.getSize(i);
                    f = paddingLeft;
                    f2 = this.mNumChars;
                    f3 = this.mSpace;
                } else if (mode2 == Integer.MIN_VALUE) {
                    size = MeasureSpec.getSize(i2);
                    f4 = this.mNumChars;
                    f5 = size * f4;
                    f6 = this.mSpace;
                } else {
                    paddingLeft = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth();
                    f = paddingLeft;
                    f2 = this.mNumChars;
                    f3 = this.mSpace;
                }
                paddingLeft = (int) (f5 + ((f6 * f4) - 1.0f));
                setMeasuredDimension(resolveSizeAndState(paddingLeft, i, 1), resolveSizeAndState(size, i2, 0));
                return;
            }
            size = (int) ((f - (f2 - (f3))) / f2);
            setMeasuredDimension(resolveSizeAndState(paddingLeft, i, 1), resolveSizeAndState(size, i2, 0));
            return;
        }
        super.onMeasure(i, i2);
    }

    @Override
    public void setOnClickListener(OnClickListener onClickListener) {
        this.mClickListener = onClickListener;
    }

    @Override
    public void setCustomSelectionActionModeCallback(ActionMode.Callback callback) {
        throw new RuntimeException("setCustomSelectionActionModeCallback() not supported.");
    }

    @Override
    protected void onDraw(Canvas canvas) {
        float f;
        CharSequence fullText = getFullText();
        int length = fullText.length();
        float[] fArr = new float[length];
        getPaint().getTextWidths(fullText, 0, length, fArr);
        String str = this.mSingleCharHint;
        float f2 = 0.0f;
        if (str != null) {
            int length2 = str.length();
            float[] fArr2 = new float[length2];
            getPaint().getTextWidths(this.mSingleCharHint, fArr2);
            for (int i = 0; i < length2; i++) {
                f2 += fArr2[i];
            }
            f = f2;
        } else {
            f = 0.0f;
        }
        int i2 = 0;
        while (i2 < this.mNumChars) {
            if (this.mPinBackground != null) {
                updateDrawableState(i2 < length, i2 == length);
                this.mPinBackground.setBounds((int) this.mLineCoords[i2].left, (int) this.mLineCoords[i2].top, (int) this.mLineCoords[i2].right,
                        (int) this.mLineCoords[i2].bottom);
                this.mPinBackground.draw(canvas);
            }
            float f3 = this.mLineCoords[i2].left + (this.mCharSize / 2.0f);
            if (length > i2) {
                if (!this.mAnimate || i2 != length - 1) {
                    canvas.drawText(fullText, i2, i2 + 1, f3 - (fArr[i2] / 2.0f), this.mCharBottom[i2], this.mCharPaint);
                } else {
                    canvas.drawText(fullText, i2, i2 + 1, f3 - (fArr[i2] / 2.0f), this.mCharBottom[i2], this.mLastCharPaint);
                }
            } else {
                String str2 = this.mSingleCharHint;
                if (str2 != null) {
                    canvas.drawText(str2, f3 - (f / 2.0f), this.mCharBottom[i2], this.mSingleCharPaint);
                }
            }
            if (this.mPinBackground == null) {
                updateColorForLines(i2 <= length);
                canvas.drawLine(this.mLineCoords[i2].left, this.mLineCoords[i2].top, this.mLineCoords[i2].right, this.mLineCoords[i2].bottom, this.mLinesPaint);
            }
            i2++;
        }
    }

    private CharSequence getFullText() {
        if (TextUtils.isEmpty(this.mMask)) {
            return getText();
        }
        return getMaskChars();
    }

    private StringBuilder getMaskChars() {
        if (this.mMaskChars == null) {
            this.mMaskChars = new StringBuilder();
        }
        int length = getText().length();
        while (this.mMaskChars.length() != length) {
            if (this.mMaskChars.length() < length) {
                this.mMaskChars.append(this.mMask);
            } else {
                StringBuilder sb = this.mMaskChars;
                sb.deleteCharAt(sb.length() - 1);
            }
        }
        return this.mMaskChars;
    }

    private int getColorForState(int... iArr) {
        return this.mColorStates.getColorForState(iArr, -7829368);
    }

    protected void updateColorForLines(boolean z) {
        if (this.mHasError) {
            this.mLinesPaint.setColor(getColorForState(16842914));
        } else if (isFocused()) {
            this.mLinesPaint.setStrokeWidth(this.mLineStrokeSelected);
            this.mLinesPaint.setColor(getColorForState(16842908));
            if (z) {
                this.mLinesPaint.setColor(getColorForState(16842913));
            }
        } else {
            this.mLinesPaint.setStrokeWidth(this.mLineStroke);
            this.mLinesPaint.setColor(getColorForState(-16842908));
        }
    }

    protected void updateDrawableState(boolean z, boolean z2) {
        if (this.mHasError) {
            this.mPinBackground.setState(new int[]{16842914});
        } else if (!isFocused()) {
            if (z) {
                this.mPinBackground.setState(new int[]{-16842908, 16842912});
            } else {
                this.mPinBackground.setState(new int[]{-16842908});
            }
        } else {
            this.mPinBackground.setState(new int[]{16842908});
            if (z2) {
                this.mPinBackground.setState(new int[]{16842908, 16842913});
            } else if (z) {
                this.mPinBackground.setState(new int[]{16842908, 16842912});
            }
        }
    }

    public void setError(boolean z) {
        this.mHasError = z;
        invalidate();
    }

    public boolean isError() {
        return this.mHasError;
    }

    public void focus() {
        requestFocus();
        ((InputMethodManager) getContext().getSystemService(INPUT_METHOD_SERVICE)).showSoftInput(this, 0);
    }

    @Override
    public void setTypeface(Typeface typeface) {
        super.setTypeface(typeface);
        setCustomTypeface(typeface);
    }

    @Override
    public void setTypeface(Typeface typeface, int i) {
        super.setTypeface(typeface, i);
        setCustomTypeface(typeface);
    }

    private void setCustomTypeface(Typeface typeface) {
        Paint paint = this.mCharPaint;
        if (paint != null) {
            paint.setTypeface(typeface);
            this.mLastCharPaint.setTypeface(typeface);
            this.mSingleCharPaint.setTypeface(typeface);
            this.mLinesPaint.setTypeface(typeface);
        }
    }

    public void setPinLineColors(ColorStateList colorStateList) {
        this.mColorStates = colorStateList;
        invalidate();
    }

    public void setPinBackground(Drawable drawable) {
        this.mPinBackground = drawable;
        invalidate();
    }

    @Override
    protected void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
        setError(false);
        if (this.mLineCoords == null || !this.mAnimate) {
            if (this.mOnPinEnteredListener == null || charSequence.length() != this.mMaxLength) {
                return;
            }
            this.mOnPinEnteredListener.onPinEntered(charSequence);
            return;
        }
        int i4 = this.mAnimatedType;
        if (i4 == -1) {
            invalidate();
        } else if (i3 > i2) {
            if (i4 == 0) {
                animatePopIn();
            } else {
                animateBottomUp(charSequence, i);
            }
        }
    }

    private void animatePopIn() {
        ValueAnimator ofFloat = ValueAnimator.ofFloat(1.0f, getPaint().getTextSize());
        ofFloat.setDuration(200L);
        ofFloat.setInterpolator(new OvershootInterpolator());
        ofFloat.addUpdateListener(valueAnimator -> {
            PinEntryEditText.this.mLastCharPaint.setTextSize((Float) valueAnimator.getAnimatedValue());
            PinEntryEditText.this.invalidate();
        });
        if (getText().length() == this.mMaxLength && this.mOnPinEnteredListener != null) {
            ofFloat.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationCancel(Animator animator) {
                }

                @Override
                public void onAnimationRepeat(Animator animator) {
                }

                @Override
                public void onAnimationStart(Animator animator) {
                }

                @Override
                public void onAnimationEnd(Animator animator) {
                    PinEntryEditText.this.mOnPinEnteredListener.onPinEntered(PinEntryEditText.this.getText());
                }
            });
        }
        ofFloat.start();
    }

    private void animateBottomUp(CharSequence charSequence, final int i) {
        this.mCharBottom[i] = this.mLineCoords[i].bottom - this.mTextBottomPadding;
        ValueAnimator ofFloat = ValueAnimator.ofFloat(this.mCharBottom[i] + getPaint().getTextSize(), this.mCharBottom[i]);
        ofFloat.setDuration(300L);
        ofFloat.setInterpolator(new OvershootInterpolator());
        ofFloat.addUpdateListener(valueAnimator -> {
            PinEntryEditText.this.mCharBottom[i] = (Float) valueAnimator.getAnimatedValue();
            PinEntryEditText.this.invalidate();
        });
        this.mLastCharPaint.setAlpha(255);
        ValueAnimator ofInt = ValueAnimator.ofInt(0, 255);
        ofInt.setDuration(300L);
        ofInt.addUpdateListener(valueAnimator -> PinEntryEditText.this.mLastCharPaint.setAlpha((Integer) valueAnimator.getAnimatedValue()));
        AnimatorSet animatorSet = new AnimatorSet();
        if (charSequence.length() == this.mMaxLength && this.mOnPinEnteredListener != null) {
            animatorSet.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationCancel(Animator animator) {
                }

                @Override
                public void onAnimationRepeat(Animator animator) {
                }

                @Override
                public void onAnimationStart(Animator animator) {
                }

                @Override
                public void onAnimationEnd(Animator animator) {
                    PinEntryEditText.this.mOnPinEnteredListener.onPinEntered(PinEntryEditText.this.getText());
                }
            });
        }
        animatorSet.playTogether(ofFloat, ofInt);
        animatorSet.start();
    }

    public void setAnimateText(boolean z) {
        this.mAnimate = z;
    }

    public void setOnPinEnteredListener(OnPinEnteredListener onPinEnteredListener) {
        this.mOnPinEnteredListener = onPinEnteredListener;
    }
}
